package cn.mfeg.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.mfeg.controllers.CollegesUserController;
import cn.mfeg.models.User;
import cn.mfeg.services.DepartmentUserService;

public class UploadDepartmentUserInfoServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	Logger log=Logger.getLogger(CollegesUserController.class);
	ApplicationContext applicationContext;
	DepartmentUserService departmentUserService;
	
	public void init() throws ServletException {
		applicationContext = new ClassPathXmlApplicationContext("spring-servlet.xml");
		departmentUserService = (DepartmentUserService) applicationContext.getBean(DepartmentUserService.class);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		try {
			String path = req.getServletContext().getRealPath("/downloadFiles");
			ServletFileUpload ss = new ServletFileUpload(new DiskFileItemFactory());// 使用系统默认的临时目录
			List<FileItem> list = ss.parseRequest(req);
			// 由于一个文件，和一个表单项目是一组
			for (FileItem item : list) {
				if (item.isFormField()) {// 普通的表表单项目 request.getparams()
					String value = item.getString(req.getCharacterEncoding());
					log.info(value);
				} else {
					String fileName = item.getName();
					fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
					File file = new File(path, fileName);
					item.write(file);//存放到磁盘中
					FileInputStream fis = new FileInputStream(file);
					Workbook workbook = new HSSFWorkbook(fis);
					/** 获取sheet */
					Sheet sheet = workbook.getSheetAt(0);
					/** 获取sheet的列数 */
					//int columnNum = sheet.getRow(0).getPhysicalNumberOfCells();
					/** 获取文件有多少行 */
					int rowNum = sheet.getLastRowNum()+1;
					//获取第二行所有数据
					for(int i=1;i<rowNum;i++){
						String departmentName = getCellStringValue(sheet.getRow(i),0);//处室名称
						String userName = getCellStringValue(sheet.getRow(i),1);//用户名
						String linkman = getCellStringValue(sheet.getRow(i),2);//联系人
						String phoneNum = getCellStringValue(sheet.getRow(i),3);//电话
						String status = getCellStringValue(sheet.getRow(i),4);//状态
						String password = getCellStringValue(sheet.getRow(i),5);//密码
						//检验该用户名是否存在
						User user = new User();
						user.setUserName(userName);
						if (!departmentUserService.validateUserName(user)) {//存在
							workbook.close();
							writer.println("用户名："+userName+"已存在！");
							return;
						}
						//将数据加入数据库
						 user.setDepartmentName(departmentName);
						 user.setLinkman(linkman);
						 user.setPhoneNum(phoneNum);
						 user.setStatus(status);
						 user.setPassword(password);
					    if (!departmentUserService.addUser(user)) {//插入失败
						    workbook.close();
						    writer.println("在导入用户:"+userName+"的信息时出现错误！");
						    return;
					    }
					}
					item.delete();
					workbook.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			writer.println("导入失败！");
			return;
		}
		 writer.println("导入成功！");
	}
	public final static String getCellStringValue(Row row, int i) {
		Cell cell = row.getCell(i);
		if (cell == null) {
			return "";
		}
		cell.setCellType(Cell.CELL_TYPE_STRING);
		if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
			return String.valueOf(cell.getNumericCellValue());
		} else {
			return String.valueOf(cell.getStringCellValue());
		}
	}
}
